﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using pinche_api.Data;
using pinche_api.Models;

namespace pinche_api.Controllers {
    /// <summary>
    /// 微信小程序
    /// </summary>
    public class WxOpenController:BaseController {
        private readonly SQLiteContext _context;
        /// <summary>
        /// 用户信息
        /// </summary>
        /// <param name="context"></param>
        public WxOpenController(SQLiteContext context) {
            _context=context;
        }
        /// <summary>
        /// wx.login登陆成功之后发送的请求
        /// </summary>
        /// <param name="code"></param>
        /// <param name="rawData"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<Result> Login([FromForm] string code,[FromForm] string rawData) {
            if(string.IsNullOrEmpty(code)) {
                throw new Exception("code无效（02）");
            }
            Result result = new Result();
            try {
                var sessionBag = WeiXinHelper.GetOpenid(code);
                if(sessionBag.errcode==0) {
                    CacheHelper.Cache.Add(sessionBag.Key,sessionBag);
                    var userInfo = _context.User.FirstOrDefault(e => e.openId==sessionBag.OpenId);
                    if(userInfo==null) {
                        userInfo=rawData.ToObject<User>();
                        userInfo.openId=sessionBag.OpenId;
                        userInfo.dateline=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        _context.User.Add(userInfo);
                        _context.SaveChanges();
                    }
                    Dictionary<string,object> keys = new Dictionary<string,object>();
                    keys.Add("sessionId",sessionBag.Key);
                    keys.Add("userInfo",userInfo);
                    result.success=true;
                    result.msg="OK";
                    result.data=keys;
                } else {
                    result.success=false;
                    result.msg=sessionBag.errcode+":"+sessionBag.errmsg;
                }
            } catch(Exception ex) {
                result.success=false;
                result.msg=ex.Message;
            }
            return Ok(result);
        }
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="sessionId"></param>
        /// <param name="rawData"></param>
        /// <param name="signature"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<Result> CheckWxOpenSignature(string sessionId,string rawData,string signature) {
            Result result = new Result();
            try {
                var checkSuccess = EncryptHelper.CheckSignature(sessionId,rawData,signature);
                result.success=checkSuccess;
                result.msg=checkSuccess ? "签名校验成功" : "签名校验失败";
            } catch(Exception ex) {
                result.success=false;
                result.msg=ex.Message;
            }
            return Ok(result);
        }
        /// <summary>
        /// 解密encryptedData
        /// </summary>
        /// <param name="type">USERINFO</param>
        /// <param name="sessionId"></param>
        /// <param name="encryptedData"></param>
        /// <param name="iv"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<Result> DecodeEncryptedData(string type,string sessionId,string encryptedData,string iv) {
            Result result = new Result();
            DecodeEntityBase decodedEntity = null;
            try {
                if(string.IsNullOrWhiteSpace(type)
                    &&string.IsNullOrWhiteSpace(sessionId)
                    &&string.IsNullOrWhiteSpace(encryptedData)
                    &&string.IsNullOrWhiteSpace(iv)) {

                    switch(type.ToUpper()) {
                        case "USERINFO"://wx.getUserInfo()
                            decodedEntity=EncryptHelper.DecodeUserInfoBySessionId(
                                sessionId,
                                encryptedData,iv);
                            break;
                        default:
                            break;
                    }
                    //检验水印
                    var checkWartmark = false;
                    if(decodedEntity!=null) {
                        checkWartmark=EncryptHelper.CheckWatermark(decodedEntity,AppConfig.APPID);
                    }

                    //注意：此处仅为演示，敏感信息请勿传递到客户端！
                    result.success=checkWartmark;
                    result.msg=string.Format("水印验证：{0}",checkWartmark ? "通过" : "不通过");

                } else {
                    result.success=false;
                    result.msg="参数不能为空";
                }
            } catch(Exception ex) {
                result.success=false;
                result.msg=ex.Message;
            }
            return Ok(result);
        }
    }
}
